package com.enjava;

import java.io.Serializable;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Transient;

import org.springframework.web.bind.annotation.PathVariable;

@ManagedBean(name = "wizardBean")
@SessionScoped
public class WizardBean implements Serializable {

	private static final long serialVersionUID = 1L;

	Curso curso = new Curso();
	Alumno alumno = new Alumno();
	Examen examen = new Examen();

	@ManagedProperty(value = "#{emf}")
	// para que un atributo no sea serializado dentro de una clase Serializable
	// hay que anteponerle la propiedad transient
	transient EMF emf;

	public EMF getEmf() {
		return emf;
	}

	public void setEmf(EMF emf) {
		this.emf = emf;
	}
	

	public Examen getExamen() {
		return examen;
	}

	public void setExamen(Examen examen) {
		this.examen = examen;
	}

	public Alumno getAlumno() {
		return alumno;
	}

	public void setAlumno(Alumno alumno) {
		this.alumno = alumno;
	}

	public Curso getCurso() {
		return curso;
	}

	public void setCurso(Curso curso) {
		this.curso = curso;
	}

	public String next() {
		FacesContext context = FacesContext.getCurrentInstance();
		Map map = context.getExternalContext().getRequestParameterMap();
		int nextPulsado = Integer.parseInt((String) map.get("valorNext"));

		switch (nextPulsado) {
		case 1:
			return "paso2?faces-redirect=true";

		case 2:
			return "paso3?faces-redirect=true";

		case 3:
			return "paso4?faces-redirect=true";

		case 4:
			return "pasoOK?faces-redirect=true";

		case 5:
			System.out.println("persistir");
			break;
		default:
			break;
		}

		return null;
	}

	public String back() {
		FacesContext context = FacesContext.getCurrentInstance();
		Map map = context.getExternalContext().getRequestParameterMap();
		int backPulsado = Integer.parseInt((String) map.get("valorBack"));

	
		switch (backPulsado) {
		case 2:
			return "paso1?faces-redirect=true";
		case 3:
			return "paso2?faces-redirect=true";
		case 4:
			return "paso3?faces-redirect=true";
		default:
			break;
		}

		return null;
	}

	public String finish() {
		curso.alumnos.add(alumno);
		curso.examenes.add(examen);

		EntityManager em = emf.getEM();
		EntityTransaction transaccion = em.getTransaction();
		transaccion.begin();
		em.persist(curso);
		transaccion.commit();

		return "pasoOK?faces-redirect=true";
	}

	public String inicio() {
		curso = new Curso();
		alumno = new Alumno();
		examen = new Examen();

		return "paso1?faces-redirect=true";
	}

}
